package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.log.LogObjectHolder;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBorrower;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBorrowerFlowInformation;
import cn.stylefeng.guns.sys.modular.system.entity.BtyXdgt;
import cn.stylefeng.guns.sys.modular.system.service.BtyBorrowerFlowInformationService;
import cn.stylefeng.guns.sys.modular.system.service.BtyBorrowerService;
import cn.stylefeng.guns.sys.modular.system.service.BtyXdService;
import cn.stylefeng.guns.sys.modular.system.service.BtyXdgtService;
import cn.stylefeng.guns.sys.modular.system.warpper.NoticeWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 借款人流水信息控制器
 *
 * @author liuy
 * @Date
 */
@Controller
@RequestMapping("/flowInfo")
public class BtyBorrowerFlowInformationController extends BaseController {

    private String PREFIX = "/modular/system/btyBorrowerFlowInfo/";
    @Resource
    private BtyXdService btyXdService;
    @Resource
    private BtyBorrowerFlowInformationService borrowerFlowInformationService;
    private String userName = "admin";
    @Resource
    private BtyXdgtService btyXdgtService;
    @Resource
    private BtyBorrowerService btyBorrowerService;
    /**
     * 是否是督导的标志off
     */
    private String off = "off";

    /**
     * 跳转到借贷款列表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "btyBorrowerFlowInfo.html";
    }

    /**
     * 跳转到借贷款列表首页
     */
    @RequestMapping("/upload")
    public String upload() {
        return PREFIX + "upload.html";
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUser(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        Boolean flag;
        JsonResult jsonResult = new JsonResult();
        try {
            flag = borrowerFlowInformationService.batchImport(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return flag;

    }

    /**
     * 导入excel
     */
    @RequestMapping("/importHk")
    @ResponseBody
    public Object importHk(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        Boolean flag;
        JsonResult jsonResult = new JsonResult();
        try {
            flag = borrowerFlowInformationService.batchImport(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return flag;
    }

    /**
     * 获取所有未还款金额
     */
    @RequestMapping("/allMoney")
    @ResponseBody
    public Double allMoney() {
        return borrowerFlowInformationService.allMoney();
    }

    /**
     * 获取借贷款列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition, String month, String status) {
        //获取用户的帐号
        Long userId = LoginContextHolder.getContext().getUserId();
        String username = LoginContextHolder.getContext().getUser().getName();
        Calendar cal = Calendar.getInstance();
        if (month == null || "".equals(month)) {
            StringBuilder sb = new StringBuilder(DateUtil.getLastMonth());
            month = sb.insert(4, "-").toString();
        } else {
            month = month.substring(0, 7);
        }
        Page<Map<String, Object>> list = this.borrowerFlowInformationService.list(condition, month, status);
        List<Map<String, Object>> mapList = list.getRecords();
        /*if (CollectionUtils.isNotEmpty(mapList)) {
            for (Map<String, Object> map : mapList) {
                map.put("remark", );
            }
        }*/
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 跳转到查询页面
     */
    @RequestMapping("lists")
    public String lists() {
        return PREFIX + "btyBorrowerFlowInfoSearch.html";
    }

    /**
     * 查询借贷款列表
     */
    @RequestMapping(value = "/listSearch")
    @ResponseBody
    public Object listSearch(String borrowerId, String loanDate) {
        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(loanDate)) {
            String[] split = loanDate.split(" - ");
            beginTime = split[0];
            endTime = split[1];
            endTime = split[1] + " 23:59:59";
        }
        Page<Map<String, Object>> list = this.borrowerFlowInformationService.listSearch(borrowerId, beginTime, endTime);
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 跳转到添加档案
     */
    @RequestMapping("/btyBorrowerFlowInfo_add")
    public String noticeAdd() {
        return PREFIX + "btyBorrowerFlowInfo_add.html";
    }

    /**
     * 跳转到修改档案
     */
    @RequestMapping("/btyXdgt_update/{id}")
    public String noticeUpdate(@PathVariable Long id, Model model) {
        BtyXdgt btyXd = this.btyXdgtService.getById(id);
        model.addAllAttributes(BeanUtil.beanToMap(btyXd));
        LogObjectHolder.me().set(btyXd);
        return PREFIX + "btyBorrowerFlowInfo_edit.html";
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(BtyBorrowerFlowInformation flowInformation) {
        if (ToolUtil.isOneEmpty(flowInformation, flowInformation.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.borrowerFlowInformationService.updateById(flowInformation);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/updateSome")
    @ResponseBody
    public Object updateSome(String id) {
        String ids[] = id.split(",");
        this.borrowerFlowInformationService.updateByIds(ids);
        return SUCCESS_TIP;
    }

    /**
     * 还款
     */
    @RequestMapping(value = "/updateHk")
    @ResponseBody
    public Object updateHk(BtyBorrowerFlowInformation borrowerFlowInformation) {
        if (ToolUtil.isOneEmpty(borrowerFlowInformation, borrowerFlowInformation.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }//获取还款金额是否和还款本金和利息相同
        BtyBorrowerFlowInformation borrowerFlowInformation1 = borrowerFlowInformationService.getById(borrowerFlowInformation.getId());
        BigDecimal hkje = new BigDecimal(borrowerFlowInformation1.getHkje());
        BigDecimal lx = new BigDecimal(borrowerFlowInformation1.getLx());
        BigDecimal je = new BigDecimal(borrowerFlowInformation1.getYhkje() == null ? "0" : borrowerFlowInformation1.getYhkje());
        BigDecimal money = hkje.add(lx);
        BigDecimal yhkje = new BigDecimal(borrowerFlowInformation.getYhkje());
        BigDecimal yhkjes = je.add(yhkje);
        if (money.compareTo(yhkjes) == 0) {
            borrowerFlowInformation.setFlag(1);
        }
        borrowerFlowInformation.setYhkje(yhkjes.toString());
        borrowerFlowInformationService.updateById(borrowerFlowInformation);
        return SUCCESS_TIP;
    }

    /**
     * 跳转到还款界面
     */
    @RequestMapping("/btyBorrowerFlowInfo_hk/{id}")
    public String hk(@PathVariable Long id, Model model) {
        BtyBorrowerFlowInformation btyXd = this.borrowerFlowInformationService.getById(id);
        model.addAllAttributes(BeanUtil.beanToMap(btyXd));
        LogObjectHolder.me().set(btyXd);
        return PREFIX + "btyBorrowerFlowInfo_hk.html";
    }

    /**
     * 新增报销档案
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@RequestParam String borrowerId, @RequestParam String loanDate, @RequestParam String summary
            , @RequestParam String debit, @RequestParam String credit, @RequestParam String balance, @RequestParam String remark) {
        BtyBorrowerFlowInformation borrowerFlowInformation = new BtyBorrowerFlowInformation();
        //通过借款人id获取借还款信息
        List<BtyBorrowerFlowInformation> list = borrowerFlowInformationService.listByBorrowerId(borrowerId);
        BigDecimal balances;
        if (list.size() == 1) {
            balances = new BigDecimal(list.get(0).getBalance());
            //贷方金额
            BigDecimal credits = new BigDecimal(credit == null | credit == "" ? "0" : credit);
            //借方金额
            BigDecimal debits = new BigDecimal(debit == null | debit == "" ? "0" : debit);
            BigDecimal ye = balances.add(credits).subtract(debits);
            borrowerFlowInformation.setBalance(ye.toString());
        } else if (list.size() > 1) {
            //获取最后一行的余额
            balances = new BigDecimal(list.get(list.size() - 1).getBalance());
            //贷方金额
            BigDecimal credits = new BigDecimal(credit == null | credit == "" ? "0" : credit);
            //借方金额
            BigDecimal debits = new BigDecimal(debit == null | debit == "" ? "0" : debit);
            BigDecimal ye = balances.add(credits).subtract(debits);
            borrowerFlowInformation.setBalance(ye.toString());

        } else {
            borrowerFlowInformation.setBalance(balance);
        }

        borrowerFlowInformation.setBorrowerId(borrowerId);
        borrowerFlowInformation.setLoanDate(loanDate);
        borrowerFlowInformation.setSummary(summary);
        borrowerFlowInformation.setDebit(debit);
        borrowerFlowInformation.setCredit(credit);
        borrowerFlowInformation.setRemark(remark);
        borrowerFlowInformation.setCreateUser(LoginContextHolder.getContext().getUserId());
        borrowerFlowInformation.setCreateTime(new Date());
        this.borrowerFlowInformationService.save(borrowerFlowInformation);
        return SUCCESS_TIP;
    }

    /**
     * 新增分期借款
     */
    @RequestMapping(value = "/addFq")
    @ResponseBody
    public Object add(BtyBorrowerFlowInformation borrowerFlowInformation) throws ParseException {
        if (ToolUtil.isOneEmpty(borrowerFlowInformation)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Long userId = LoginContextHolder.getContext().getUserId();
        //通过借款人id获取借还款信息
//        List<BtyBorrowerFlowInformation> list = borrowerFlowInformationService.listByBorrowerId(borrowerFlowInformation.getBorrowerId());
//        BigDecimal balances;
//        if (list.size() == 1) {
//            balances = new BigDecimal(list.get(0).getBalance());
//            Long id = list.get(0).getId();
//            String credit = list.get(0).getCredit();
//            //贷方金额
//            BigDecimal credits = new BigDecimal(credit == null | credit == "" ? "0" : credit);
//            //本金
//            String bj = borrowerFlowInformation.getBj();
//            BigDecimal bjs = new BigDecimal(bj == null | bj == "" ? "0" : bj);
//            credits = credits.add(bjs);
//            borrowerFlowInformation.setCredit(credits.toString());
//            BigDecimal ye = balances.add(bjs);
//            borrowerFlowInformation.setBalance(ye.toString());
//            borrowerFlowInformation.setId(id);
//        } else if (list.size() > 1) {
//            //获取最后一行的余额
//            balances = new BigDecimal(list.get(list.size() - 1).getBalance());
//            Long id = list.get(list.size() - 1).getId();
//            borrowerFlowInformation.setId(id);
//            String credit = list.get(list.size() - 1).getCredit();
//            //贷方金额
//            BigDecimal credits = new BigDecimal(credit == null | credit == "" ? "0" : credit);
//            //本金
//            String bj = borrowerFlowInformation.getBj();
//            BigDecimal bjs = new BigDecimal(bj == null | bj == "" ? "0" : bj);
//            credits = credits.add(bjs);
//            borrowerFlowInformation.setCredit(credits.toString());
//            BigDecimal ye = balances.add(bjs);
//            borrowerFlowInformation.setBalance(ye.toString());
//            borrowerFlowInformation.setId(id);
//        }


        //通过月利率和分期数计算每月应还的本金和利息
        String bj = borrowerFlowInformation.getBj();
        BigDecimal bjs = new BigDecimal(bj == null | bj == "" ? "0" : bj);
        String yll = borrowerFlowInformation.getYll();
        String ylls = yll.replace("%", "");
        Float f = Float.valueOf(ylls) / 100;
        BigDecimal decimal = new BigDecimal(f);
        Integer fqs = borrowerFlowInformation.getFqs();
        //每月利息=本金*月利率
        BigDecimal lx = bjs.multiply(decimal);
        Double lxs = lx.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        //每月还款本金=本金/分期数
        BigDecimal hkje = bjs.divide(new BigDecimal(fqs), 2, BigDecimal.ROUND_HALF_UP);
        Double hkjes = hkje.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String borrowerId = borrowerFlowInformation.getBorrowerId();
        String loanDate = borrowerFlowInformation.getLoanDate();
        String summary = borrowerFlowInformation.getSummary();
        //获取日期加一个月的时间
        String subMonth = DateUtil.subMonth(loanDate);
        //截取年月
        String months = subMonth.substring(0, 7);
        //截取月份
        // int month = Integer.parseInt(loanDate.split("[-]")[1]) + 1;
        int num = 0;
        //根据分期数批量插入数据库
        for (int i = 0; i < fqs; i++) {
            num = borrowerFlowInformationService.insertFq(UUIDUtils.getId(), borrowerId, loanDate, bj, yll, months, hkjes.toString(), lxs.toString(), new Date(), userId, summary);
            subMonth = DateUtil.subMonth(subMonth);
            months = subMonth.substring(0, 7);
        }
//        if(num>0){
//            borrowerFlowInformation.setYll(null);
//            borrowerFlowInformation.setFqs(null);
//            borrowerFlowInformation.setBj(null);
//            borrowerFlowInformation.setLoanDate(null);
//            this.borrowerFlowInformationService.updateById(borrowerFlowInformation);
//        }
        return SUCCESS_TIP;
    }

    /**
     * 档案详情
     */
    @RequestMapping("/info")
    @ResponseBody
    public Object getThemeInfo(@RequestParam String id) {
        if (ToolUtil.isEmpty(id)) {
            throw new RequestEmptyException();
        }
        BtyBorrowerFlowInformation btyXd = this.borrowerFlowInformationService.getById(id);
        return btyXd;
    }

    /**
     * 删除报销档案
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long id) {
        this.borrowerFlowInformationService.removeById(id);
        return SUCCESS_TIP;
    }

    /**
     * 批量删除报销档案
     */
    @RequestMapping(value = "/batchDelete")
    @ResponseBody
    public Object batchDelete(@RequestParam String ids) {
        String id[] = ids.split(",");
        for (int i = 0; i < id.length; i++) {
            this.borrowerFlowInformationService.removeById(id[i]);
        }
        // this.borrowerFlowInformationService.removeById(id);
        return SUCCESS_TIP;
    }
    /**
     * 查询店名
     */
//    @RequestMapping(value = "/getDm")
//    @ResponseBody
//    public List<BtyXd> getDm(){
//        List<BtyXd> list=btyXdService.dmList();
//        return list;
//    }

    /**
     * 获取借款人
     */
    @RequestMapping(value = "/borrowerInfo")
    @ResponseBody
    public List<BtyBorrowerFlowInformation> borrowerInfo() {
        Long userId = LoginContextHolder.getContext().getUserId();
        //获取用户的帐号
        String account = LoginContextHolder.getContext().getUser().getName();
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<BtyBorrowerFlowInformation> list = borrowerFlowInformationService.borrowerInfo();

        return list;
    }

    /**
     * 获取已借贷款人数
     */
    @RequestMapping("/borrowed")
    @ResponseBody
    public List<BtyBorrower> borrowed() {
        List<BtyBorrower> list = btyBorrowerService.borrowed();
        return list;
    }

    /**
     * 获取未借贷款人数
     */
    @RequestMapping("/notBorrowed")
    @ResponseBody
    public List<BtyBorrower> notBorrowed() {
        List<BtyBorrower> list = btyBorrowerService.notBorrowed();
        return list;
    }

}
